import { useState, useEffect } from 'react';
import { App, Table, Button, Space, Modal, Form, Input, Radio, Select, Cascader } from 'antd';
import { MainLayout } from '~/layouts/MainLayout';
import { questionApi, categoryApi } from '~/services/api';

export default function Questions() {
  const { message, modal } = App.useApp();
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [editingRecord, setEditingRecord] = useState<any>(null);
  const [categories, setCategories] = useState([]);

  // 添加分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 修改 fetchData 方法
  const fetchData = async (page = 1, pageSize = 10) => {
    try {
      const res: any = await questionApi.list({
        page,
        size: pageSize
      });
  
      if (!res.data?.items) {
        message.warning('获取数据异常');
        return;
      }
  
      const processedData = res.data.items.map((item: any) => ({
        ...item,
        key: item.question_id || item.id
      }));
  
      setData(processedData);
      setPagination({
        current: page,
        pageSize: pageSize,  // Add pageSize to pagination state
        total: res.data.total || 0
      });
    } catch (error) {
      console.error('获取数据失败:', error);
      message.error('获取数据失败');
    }
  };

  const fetchCategories = async () => {
    try {
      const res = await categoryApi.list({});
      const formatCategories: any = (items: any[]) => {
        return items.map(item => ({
          label: item.name,
          value: item.id,
          isLeaf: item.level >= 6,  // 根据层级判断是否为叶子节点
          level: item.level,
          loading: false
        }));
      };
      setCategories(formatCategories(res.data?.items || []));
    } catch (error) {
      console.error('获取分类失败:', error);
      message.error('获取分类失败');
    }
  };

  useEffect(() => {
    fetchData();
    fetchCategories();
  }, []);

  const handleAdd = async ({categoryPath, ...values}: any) => {
    try {
      setLoading(true);
      const knowledge_point_code = categoryPath?.join('-') || '';
      // 获取选中的分类名称
      const knowledge_point_label = categoryPath?.map((id: number) => {
        const findLabel = (options: any[]): string => {
          for (const opt of options) {
            if (opt.value === id) return opt.label;
            if (opt.children) {
              const label = findLabel(opt.children);
              if (label) return label;
            }
          }
          return '';
        };
        return findLabel(categories);
      }).join(' / ') || '';

      await questionApi.create({
        ...values,
        knowledge_point_code,
        knowledge_point_label
      });
      message.success('创建成功');
      setVisible(false);
      form.resetFields();
      fetchData();
    } catch (error) {
      console.error('Create error:', error);
      message.error('创建失败');
    } finally {
      setLoading(false);
    }
  };

  const handleEdit = async ({categoryPath, ...values}: any) => {
    try {
      setLoading(true);
      const knowledge_point_code = categoryPath?.join('-') || '';
      // 获取选中的分类名称
      const knowledge_point_label = categoryPath?.map((id: number) => {
        const findLabel = (options: any[]): string => {
          for (const opt of options) {
            if (opt.value === id) return opt.label;
            if (opt.children) {
              const label = findLabel(opt.children);
              if (label) return label;
            }
          }
          return '';
        };
        return findLabel(categories);
      }).join(' / ') || '';

      await questionApi.update(editingRecord.question_id, {
        ...values,
        knowledge_point_code,
        knowledge_point_label
      });
      message.success('更新成功');
      setVisible(false);
      setEditingRecord(null);
      form.resetFields();
      fetchData();
    } catch (error) {
      console.error('Update error:', error);
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    {
      title: '题目ID',
      dataIndex: 'question_id',
      key: 'question_id',
    },
    {
      title: '题目内容',
      dataIndex: 'question_desc',
      key: 'question_desc',
      ellipsis: true,
    },
    {
      title: '答案选项',
      key: 'options',
      render: (_: any, record: any) => {
        const options = [];
        for (let i = 1; i <= 6; i++) {
          const optionKey = `option_${i}`;
          if (record[optionKey] && record[optionKey].trim() !== '') {
            options.push(
              <div key={optionKey}>
                {`${String.fromCharCode(64 + i)}. ${record[optionKey]}`}
              </div>
            );
          }
        }
        return options;
      },
    },
    {
      title: '知识点打标',
      dataIndex: 'knowledge_point_label',
      key: 'knowledge_point_label',
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space key={`${record.question_id}-actions`}>
          <Button
            type="link"
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button type="link" danger onClick={() => {
            modal.confirm({
              title: '确认删除',
              content: '确定要删除该题目吗？',
              onOk: async () => {
                try {
                  await questionApi.delete(record.question_id);
                  message.success('删除成功');
                  fetchData();
                } catch (error) {
                  message.error('删除失败');
                }
              },
            });
          }}>删除</Button>
        </Space>
      ),
    }
  ];

  // 添加查找选项的辅助函数
  const findOptionById = (options: any[], id: string): any => {
    for (const option of options) {
      if (option.value.toString() === id) {
        return option;
      }
      if (option.children) {
        const found = findOptionById(option.children, id);
        if (found) return found;
      }
    }
    return null;
  };
  
  // 添加加载编辑分类的函数
  // 修改加载编辑分类的函数
  const loadEditCategories = async (record: any) => {
    const categoryIds = record.knowledge_point_code?.split('-') || [];
    let currentCategories = [...categories];
  
    for (let i = 0; i < categoryIds.length; i++) {
      const currentId = categoryIds[i];
      if (currentId && i > 0) {
        const parentId = categoryIds[i - 1];
        const parentLevel = String(i);
        const res = await categoryApi.list({
          parentId,
          parentLevel
        });
  
        // 查找并更新父节点的子节点
        const findAndUpdateParent = (items: any[]): boolean => {
          for (let j = 0; j < items.length; j++) {
            if (items[j].value.toString() === parentId) {
              items[j].children = (res.data?.items || []).map((child: any) => ({
                label: child.name,
                value: child.id,
                isLeaf: child.level >= 6,
                level: child.level
              }));
              return true;
            }
            if (items[j].children && findAndUpdateParent(items[j].children)) {
              return true;
            }
          }
          return false;
        };
  
        findAndUpdateParent(currentCategories);
      }
    }
  
    setCategories(currentCategories);
    return categoryIds;
  };
  
  // 修改 showModal 函数
  const showModal = async (record?: any) => {
    
    
    if (record) {
      const categoryIds = await loadEditCategories(record);
      // 先重置表单和状态
      form.resetFields();
      setEditingRecord(null);
      // 使用 setFieldsValue 设置表单值
      form.setFieldsValue({
        ...record,
        categoryPath: categoryIds
      });
      setEditingRecord(record);
    } else {
      // 重新获取初始分类数据
      await fetchCategories();
      // 先重置表单和状态
      form.resetFields();
      setEditingRecord(null);
    }
    setVisible(true);
  };

  return (
    <MainLayout>
      <div className="bg-white p-6 rounded-lg">
        <div className="flex justify-between mb-4">
          <h1 className="text-2xl">题库管理</h1>
          <Button type="primary" onClick={() => showModal()}>
            新增题目
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={data}
          rowKey={(record) => record.question_id || record.id}
          pagination={{
            ...pagination,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page, pageSize) => {
              fetchData(page, pageSize);
            }
          }}
        />

        <Modal
          title={editingRecord ? '编辑题目' : '新增题目'}
          open={visible}
          onCancel={() => {
            setVisible(false);
            setEditingRecord(null);
            form.resetFields();
            // 重新获取初始分类数据
            fetchCategories();
          }}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            onFinish={editingRecord ? handleEdit : handleAdd}
            layout="vertical"
          >
            <Form.Item name="question_desc" label="题目内容" rules={[{ required: true }]}>
              <Input.TextArea rows={4} />
            </Form.Item>

            <Form.Item name="categoryPath" label="知识点打标" rules={[{ required: true }]}>
              <Cascader
                options={categories}
                // 修改 loadData 函数的实现
                loadData={async (selectedOptions) => {
                  const targetOption: any = selectedOptions[selectedOptions.length - 1];
                
                  try {
                    const res = await categoryApi.list({
                      parentId: targetOption.value,
                      parentLevel: targetOption.level
                    });
                    const children = res.data?.items || [];
                    targetOption.children = children.map((item: any) => ({
                      label: item.name,
                      value: item.id,
                      isLeaf: children.length === 0 || item.level >= 6,
                      level: item.level
                    }));
                  } catch (error) {
                    console.error('获取子分类失败:', error);
                    message.error('加载子分类失败');
                  }
                  targetOption.loading = false;
                  setCategories([...categories]);
                }}
                changeOnSelect
                placeholder="请选择知识点分类"
              />
            </Form.Item>

            <p className='ant-col pb-2'>答案选项</p>
            <div style={{ borderColor: '#d9d9d9' }} className="border rounded-lg p-4 bg-gray-50 mb-6">
              <div className="grid grid-cols-2 gap-4">
                {['A', 'B', 'C', 'D', 'E', 'F'].map((letter, index) => {
                  const optionKey = `option_${index + 1}`;
                  return (
                    <Form.Item
                      key={optionKey}
                      name={optionKey}
                      label={`选项${letter}`}
                      className="mb-2"
                    >
                      <Input placeholder={`请输入选项${letter}`} />
                    </Form.Item>
                  );
                })}
              </div>
            </div>
            <Form.Item className="text-right mb-0">
              <Space>
                <Button onClick={() => setVisible(false)}>取消</Button>
                <Button type="primary" htmlType="submit" loading={loading}>
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </MainLayout>
  );
}